package cn.org.timespace.ons.socket.mina.util;

import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.org.timespace.easyframe.util.StringUtils2;
import cn.org.timespace.ons.action.base.MachinesModel;
import cn.org.timespace.ons.action.base.MomModel;
import cn.org.timespace.ons.action.policy.MomStatusModel;
import cn.org.timespace.ons.inside.webservice.client.WebServiceClient;
import cn.org.timespace.ons.service.base.MachinesApplyService;
import cn.org.timespace.ons.service.base.MachinesConfService;
import cn.org.timespace.ons.service.base.MachinesService;
import cn.org.timespace.ons.service.base.MomService;
import cn.org.timespace.ons.service.policy.MachinesMomService;
import cn.org.timespace.ons.service.policy.MomStatusService;
import cn.org.timespace.ons.socket.mina.filter.ESCardProtocalPack;
import cn.org.timespace.ons.util.SystemContext;
import cn.org.timespace.ons.vo.base.AppleServer;
import cn.org.timespace.ons.vo.base.Machines;
import cn.org.timespace.ons.vo.base.MachinesConf;
import cn.org.timespace.ons.vo.base.MachinesMom;
import cn.org.timespace.ons.vo.base.Mom;
import cn.org.timespace.ons.vo.policy.MomStatus;

public class ProcessPackage {
	private final static Log log = LogFactory.getLog(ProcessPackage.class);
	
	/**
	 * 获取信息终端的配置信息
	 */
	public static String getMachinesConf(String machinesGroupID){
		log.debug("机器的组合ID信息：" + machinesGroupID);
		String mcString = "";
		MachinesConfService machinesConfService = (MachinesConfService)SystemContext.getApplicationContext().getBean("machinesConfService");
		//信息终端的配置集合
		List<MachinesConf> mcList = machinesConfService.findConfByMachinesID(machinesGroupID);
		if(mcList != null && mcList.size()>0){
			for(MachinesConf mc:mcList){
				mcString += mc.getConfValue();
			}
		}
		return mcString;
	}
	
	/**
	 * 根据信息终端的三码,查询是否存在此信息终端
	 */
	public static Machines getMachinesFId(String machinesGroupID){
		log.debug("信息终端的三码组合ID信息：" + machinesGroupID);
		String mcString = "";
		MachinesService machinesService = (MachinesService)SystemContext.getApplicationContext().getBean("machinesService");
		//根据信息终端的三码组合ID,及初次时间是否为空，获取信息终端
		Machines machines = machinesService.findByCondition(machinesGroupID);
		return machines;
	}
	
	/**
	 * 根据信息终端ID，查询其它申请的应用平台,
	 * 应用平台地址用IPPORT形式，并用十六进制表示,多个地址用逗号隔开
	 * @param machinesid
	 * @return
	 */
	public static String getMSInfo(String machinesGroupID){
		String result = "<APPCONTENT>";
		result += "<DEVICENO>"+machinesGroupID+"</DEVICENO>";
		String apples = "";
		MachinesApplyService machinesApplyService = (MachinesApplyService)SystemContext.getApplicationContext().getBean("machinesApplyService");
		ArrayList<AppleServer> asList = machinesApplyService.findAppleServerByMachinesID(machinesGroupID);
		for(AppleServer as:asList){
			String appleServerID = as.getAsid();//应用平台ID 20位
			String interType = StringUtils2.convertNullToString(as.getInterType());
			String interAddress = StringUtils2.convertNullToString(as.getInterAddress());
			String interMethod = StringUtils2.convertNullToString(as.getInterMethod());
			apples += "<APP>";
			apples +="<APPID>"+appleServerID+"</APPID>";
			apples +="<APPSORT>"+interType+"</APPSORT>";
			apples +="<APPADDR>"+interAddress+"</APPADDR>";
			apples +="<APPPARM>"+interMethod+"</APPPARM>";
			apples += "</APP>";
		}
		result +=apples;
		result +="</APPCONTENT>";
		return result;
	}
	
	/**
	 * 根据信息终端获取数据交换地址
	 * @param machinesid
	 * @return
	 */
	private static int count = 0;//取数据交换地址次数
	private static String flag = "1";//向取得数据交换地址发送信息终端信息是否成功 0 成功，1失败
	private static List<MomStatus> momStatusList = null;
	public static String getMomAddr(String machinesGroupID,String apples){
		String momAddr = "";
		MomStatus momStatus = new MomStatus();
		Random random = new Random();
		Mom mom = null;
		MomStatusService momStatusService = (MomStatusService)SystemContext.getApplicationContext().getBean("momStatusService");
		MomStatusModel momStatusModel = new MomStatusModel();
		momStatusModel.setStatus("0");
		momStatusList = momStatusService.findByCondition(momStatusModel);
		
		if(momStatusList !=null && momStatusList.size()>0){
			int momSize = momStatusList.size();
			int index = random.nextInt(momSize);
			momStatus = momStatusList.get(index);
			MomService momService = (MomService)SystemContext.getApplicationContext().getBean("momService");
			mom = momService.findById(momStatus.getMomid());
		}
		if(mom != null){
			String ip=mom.getIpAddress();
			String dns = mom.getDns();
			String port=mom.getPort();
			String momid = mom.getMomid();
			flag = sendMessage(ip, port,apples);
			count=count+1;
			if(flag.equals("1") && count <3){
				getMomAddr(machinesGroupID,apples);
			}
			if(flag.equals("0")){
				String ipAddress = ProcessPackage.getHexIPString(ip);
				String portAddress = ProcessPackage.getHex(Integer.parseInt(port), 4);
				String dnsAddress = ProcessPackage.StrAddLengthZero(30, dns);
				momAddr= momid+";"+ipAddress+dnsAddress+portAddress;
			}
			
		}
		count = 0;
		return momAddr;
	}
	
	
	/**
	 * 向数据交换中心发送信息终端及信息终端申请的应用平台信息
	 * @param msg
	 * @throws Exception 
	 * @throws MalformedURLException 
	 * */
	public static String sendMessage(String ip,String port,String apples) {
		log.debug("向数据交换平台"+ip+":"+port+"发送消息： "+apples);
		WebServiceClient service = new WebServiceClient(ip,port);
		
		try {
			
			String result = service.sendMessage(new Object[]{apples});
			
			if(result != null && result.equals("0")){
				log.debug("发送消息成功");
				
				return result;
			}else{
				log.debug("发送消息失败，未取到返回值");
				return result;
			}
		} catch (MalformedURLException e) {
			log.error("向平台发送消息( "+apples + ")失败:" + e);
			e.printStackTrace();
			return "1";
		} catch (Exception e) {
			log.error("向平台发送消息("+apples + ")失败:" + e);
			e.printStackTrace();
			return "1";
		}
	}
	
	/**
	 * 根据信息终端的组合ID，查询主键ID
	 * @param machinesGroupID
	 * @return
	 */
	public static String getMachinesID(String machinesGroupID){
		String msid = "";
		MachinesModel maModel = new MachinesModel();
		maModel.setMachinesID(machinesGroupID);
		MachinesService machinesService = (MachinesService)SystemContext.getApplicationContext().getBean("machinesService");
		List<Machines> listMachies = machinesService.findByCondition(maModel);
		if(listMachies != null && listMachies.size()>0){
			msid = listMachies.get(0).getMid();
		}
		return msid;
	}
	
	/**
	 * 根据数据交换的IP和端口，查询数据交换的主键ID
	 * @param machinesGroupID
	 * @return
	 */
	public static String getMomID(String momAddr){
		String momid = "";
		String ips[] = momAddr.split(",");
		String ip = ips[0];
		String port = ips[0];
		MomModel momModel = new MomModel();
		momModel.setIpAddress(ip);
		momModel.setPort(port);
		MomService momService = (MomService)SystemContext.getApplicationContext().getBean("momService");
		List<Mom> listMom = momService.findByCondition(momModel);
		if(listMom != null && listMom.size()>0){
			momid = listMom.get(0).getMomid();
		}
		return momid;
	}
	
	/**
	 * 把正常的IP转换为12位长的16进制
	 * @param machinesGroupID
	 * @return
	 */
	public static String getHexIPAddress(String momAddr){
		String momIP = "";
		String ipLong[] = momAddr.split(",");
		String ips = ipLong[0];
		String port = ipLong[1];
		String[] ip = ips.split("\\.");
		for(String jie:ip){
			momIP +=ProcessPackage.getHex(Integer.parseInt(jie), 2);
		}
		momIP +=ProcessPackage.getHex(Integer.parseInt(port), 4);
		return momIP;
	}
	
	/**
	 * 把正常的IP转换为8位长的16进制
	 * @param machinesGroupID
	 * @return
	 */
	public static String getHexIPString(String ipAddress){
		String momIP = "";
		String[] ip = ipAddress.split("\\.");
		for(String jie:ip){
			momIP +=ProcessPackage.getHex(Integer.parseInt(jie), 2);
		}
		return momIP;
	}
	
	/**
	 * 插入信息终端分配信息
	 * @param machinesGroupID
	 * @param momAddr
	 */
	public static void addMachinesMom(String  machinesGroupID,String momid) {
		MachinesMomService machinesMomService = (MachinesMomService)SystemContext.getApplicationContext().getBean("machinesMomService");
		MachinesMom machinesMom = null;//信息终端分配信息
		String msid = ProcessPackage.getMachinesID(machinesGroupID); 
		machinesMom = machinesMomService.findByMsId(msid);
		if(machinesMom == null){
			machinesMom = new MachinesMom();
		}
		machinesMom.setMsid(msid);
		machinesMom.setMomid(momid);
		machinesMom.setStatus(1);//
		machinesMom.setSentTime(new Date());
		log.debug("插入信息终端分配信息：" + msid+" "+momid);
		
		
		//保存信息终端分配数据交换记录
		machinesMomService.inMM(machinesMom);
	}
	
	/**
	 * 插入信息终端分配信息
	 * @param machinesMom
	 */
	public static void addMachinesMom(MachinesMom machinesMom) {
		log.debug("插入信息终端分配信息：" + machinesMom.getMomid()+" "+machinesMom.getMsid());
		MachinesMomService machinesMomService = (MachinesMomService)SystemContext.getApplicationContext().getBean("machinesMomService");
		//保存话单
		machinesMomService.inMM(machinesMom);
	}
	
	
	
	/**
	 * 根据接收包结构取得回复包（机器号和功能号相同）
	 * @param pack
	 * @return
	 */
	public static ESCardProtocalPack getPackReplay(ESCardProtocalPack pack) {
		ESCardProtocalPack packReplay = new ESCardProtocalPack();
		packReplay.setSyncFrame(ESCardProtocalPack.SYNC_FRAME_NAME_DOWN);
		packReplay.setMachineNo(pack.getMachineNo());
		packReplay.setFunctionNo(pack.getFunctionNo());
		return packReplay;
	}
	
	/**
	 * 字符串长度不足时，在最前面补 0
	 * @param digits  字符串应有长度
	 * @param str  字符串
	 * */
	public static String StrAddLength(int digits,String str){
		int len = str.length();
		if(len < digits){
			StringBuffer sb = new StringBuffer();
			for(int j = 0; j < digits - len; j++){
				sb.append("0");
			}
			str = sb.toString() + str;
		}
		return str;
	}
	
	/**
	 * 字符串长度不足时，在最后面补空格
	 * @param digits  字符串应有长度
	 * @param str  字符串
	 * */
	public static String StrAddLengthZero(int digits,String str){
		str = StringUtils2.convertNullToString(str);
		int len = str.length();
		if(len < digits){
			StringBuffer sb = new StringBuffer();
			for(int j = 0; j < digits - len; j++){
				sb.append(" ");
			}
			str = str+sb.toString();
		}
		return str;
	}
	
	/**
	 * 判断输入流是否以同步帧(SyncFrame)开头
	 * @param in
	 * @return
	 */
	public static boolean isStartWithSyncFrame(String inStr) {
		
		if(inStr == null)
			return false;
		
		if(inStr.startsWith(ESCardProtocalPack.SYNC_FRAME_NAME_UP) || inStr.startsWith(ESCardProtocalPack.SYNC_FRAME_NAME_DOWN))
			return true;
		
		return false;
	}
	
	/**
	 * 根据传入的整数和要返回的十六进制位数，如果不够数时，用0在前面补充
	 * @param i
	 * @param length
	 * @return
	 */
	public static String getHex(Integer i,int length){
		String hex = Integer.toHexString(i).toUpperCase();
		return StrAddLength(length,hex);
	}
	
	
	
	public static void main(String[] args) {
		//测试用
		for(int i = 0; i < 2000; i++) {
			//ProcessPackage.sendMessage("0000818819/110528070013/1/100000;");
		}
		
		try {
		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		Date dateCardRecord = format.parse("110528070013");
		
		Date dateActiveMsg = format.parse("110528070514");
		
		System.out.println((dateActiveMsg.getTime() - dateCardRecord.getTime()) / 1000);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
